package com.haixiaoke.smartLock.tianwanghulian;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.haixiaoke.common.core.redis.RedisCache;
import com.haixiaoke.domain.*;
import com.haixiaoke.smartLock.base.SmartLockBasicsService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 天网互联智能锁接口
 * xiaolong
 * 2023-05-25
 */
@Service
public class SmartLockTWHlService implements SmartLockBasicsService {
    @Autowired
    private RedisCache redisCache;
    @Value("${tianWangHulian.url}")
    private String tianWangHuLianCallbackUrl;
    @Value("${tianWangHulian.appKey}")
    private String tianWangHuLianAppKey;
    @Value("${tianWangHulian.secret}")
    private String tianWangHuLianSecret;


    /**
     * 获取PasS平台token
     *
     * @return
     */
    public String getToken() {
        String paaSToken = redisCache.getCacheObject("sys_tianWangHuLianToken");
        if (StringUtils.isEmpty(paaSToken)) {
            try {
                HttpPost httpPost = new HttpPost(tianWangHuLianCallbackUrl + "/api/login.do");
                CloseableHttpClient httpClient = HttpClients.createDefault();
                BasicResponseHandler handler = new BasicResponseHandler();
                Map<String, String> params = new HashMap<>();
                params.put("appKey", tianWangHuLianAppKey);
                params.put("secret", tianWangHuLianSecret);
                //设置请求格式
                StringEntity entity = new StringEntity(JSON.toJSONString(params), "utf-8");//解决中文乱码问题
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
                //执行POST请求
                String execute = httpClient.execute(httpPost, handler);
                JSONObject resultJson = JSON.parseObject(execute);
                Object data = resultJson.get("data");
                JSONObject jsonObject = JSON.parseObject(data.toString());
                Object token = jsonObject.get("token");
                redisCache.setCacheObject("sys_tianWangHuLianToken", token.toString(), 30, TimeUnit.MINUTES);
                return token.toString();
            } catch (Exception e) {
                return "获取失败";
            }
        }
        return paaSToken;
    }

    /**
     * 获取智能锁信息
     */
    @Override
    public String getSmartLock(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        String result = HttpRequest.get(tianWangHuLianCallbackUrl + "/api/deviceList.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 获取智能锁门卡信息
     */
    @Override
    public String getSmartLockDetails(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        String result = HttpRequest.get(tianWangHuLianCallbackUrl + "/api/cardInfo.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 获取智能锁临时密码权限信息
     */
    @Override
    public String getLockPassword(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        String result = HttpRequest.get(tianWangHuLianCallbackUrl + "/api/temporaryPassword.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 获取智能锁临时蓝牙权限信息
     */
    @Override
    public String getBluetooth(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        String result = HttpRequest.get(tianWangHuLianCallbackUrl + "/api/bluetooth/unlockAuthority.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 删除智能锁蓝牙权限
     */
    @Override
    public String deleteBle(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        List<Object> identifications = new ArrayList<>();
        String token = this.getToken();
        //天网互联密码标识
        identifications.add(smartLock.getIdentification());
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identifications", identifications);
        String result = HttpRequest.delete(tianWangHuLianCallbackUrl + "/api/bluetooth/unlockAuthority.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 新增蓝牙授权信息
     *
     * @param smartLock 蓝牙授权信息
     * @return 结果
     */
    @Override
    public String addBluetooth(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Object> passwordList = new ArrayList<>();
        String token = this.getToken();
        map.put("identification", smartLock.getIdentification());
        map.put("startTime", smartLock.getStartTime());
        map.put("endTime", smartLock.getEndTime());
        passwordList.add(map);
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("passwordList", passwordList);
        String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/bluetooth/unlockAuthority.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 新增智能锁指纹授权信息和授权指纹
     *
     * @param smartLock 智能锁指纹授权信息
     * @return 结果
     */
    @Override
    public String addFingerprint(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        //添加指纹数据
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        hashMap.put("fingerprintData", smartLock.getFingerprint());
        String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/saveFingerprintInfo.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 下发指纹信息
     *
     * @param smartLock 智能锁指纹授权信息
     * @return 结果
     */
    @Override
    public String sendFingerprint(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        //下发指纹数据
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/sendFingerprintData.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 删除指纹授权信息
     *
     * @param smartLock 需要删除的智能锁指纹授权信息主键
     * @return 结果
     */
    @Override
    public String deleteFingerprint(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        String result = HttpRequest.delete(tianWangHuLianCallbackUrl + "/api/deleteFingerprintInfo.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 生产离线密码
     *
     * @param smartLock@return
     */
    @Override
    public String offlinePassword(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        //密码时间：passTime 计算好的有效时间 范围：1到999(第一位为5以下则代表分钟数，第一位为5或以上，则应减去5后代表小时数)(必填)
        hashMap.put("passTime", smartLock.getPassTime());
        String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/offlinePassword.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 远程开锁
     *
     * @param smartLock@return
     */
    @Override
    public String remoteUnlock(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/remoteUnlock.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;

    }

    /**
     * 智能锁密码授权
     *
     * @param smartLock 智能锁密码授权信息
     * @return 结果
     */
    @Override
    public String addPassword(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        hashMap.put("password", smartLock.getPassword());
        hashMap.put("startTime", smartLock.getStartTime());
        hashMap.put("endTime", smartLock.getEndTime());
        String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/temporarySinglePassword.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 删除智能锁密码授权信息和删除密码授权
     *
     * @param smartLock@return
     */
    @Override
    public String deletePwd(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        String result = HttpRequest.delete(tianWangHuLianCallbackUrl + "/api/temporarySinglePassword.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 授权门卡
     *
     * @param smartLock 智能锁门卡授权信息
     * @return 结果
     */
    @Override
    public String addCard(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        //授权身份证/授权CPU卡
        Integer type = smartLock.getCardType();//1:授权身份证 2：授权CUP卡
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        hashMap.put("startTime", smartLock.getStartTime());
        hashMap.put("endTime", smartLock.getEndTime());
        //卡类型：0CPU卡(普通门卡) 1身份证
        if (SmartLock.IDENTITY_CARD_TYPE.equals(type)) {
            hashMap.put("cardType", 1);
            hashMap.put("cardNum", smartLock.getCardNumber());
            String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/singleIdentity.do")
                    .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                    .body(JSONObject.toJSONString(hashMap))
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            return result;
        } else {
            hashMap.put("cardType", 0);
            hashMap.put("cardNum", smartLock.getCardNumber());
            String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/singleCard.do")
                    .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                    .body(JSONObject.toJSONString(hashMap))
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            return result;
        }
    }

    /**
     * 删除智能锁密码授权信息和删除密码授权
     *
     * @param smartLock@return
     */
    @Override
    public String deleteCard(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        String result = HttpRequest.delete(tianWangHuLianCallbackUrl + "/api/singleCard.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    /**
     * 查询蓝牙开锁密钥
     *
     * @param smartLock
     * @return
     */
    @Override
    public String getUnlockKey(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("identification", smartLock.getIdentification());
        String result = HttpRequest.get(tianWangHuLianCallbackUrl + "/api/bluetooth/unlockKey.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .form(hashMap)
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }

    @Override
    public String addFaceImage(SmartLock smartLock) {
        return null;
    }

    @Override
    public String deleteFace(SmartLock smartLock) {
        return null;
    }

    @Override
    public String getTaskList(SmartLock smartLock) {
        return null;
    }

    /**
     * 删除所有授权
     *
     * @param smartLock 智能锁设备信息
     * @return
     */
    public String deleteSmartLockByLockId(SmartLock smartLock) {
        Map<String, Object> hashMap = new HashMap<String, Object>();
        String token = this.getToken();
        hashMap.put("deviceNum", smartLock.getSn());
        hashMap.put("authType", 0);//0：恢复出厂，清除所有开锁方式的权限
        String result = HttpRequest.post(tianWangHuLianCallbackUrl + "/api/clearPassword.do")
                .header("Authorization", token)//头信息，多个头信息多次调用此方法即可
                .body(JSONObject.toJSONString(hashMap))
                .timeout(20000)//超时，毫秒
                .execute().body();
        return result;
    }
}
